﻿#include "TcpClient.h"

#include <QBuffer>
#include <QDateTime>
#include <QImage>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMetaType>
#include <QTimer>
#include <QThread>
#include "MainWindow.h"

TcpClient::TcpClient(QObject *parent) :
    QObject(parent),
    m_sendMsgLenCnt(0),
    m_revMsgLenCnt(0),
    m_isOnline(false),
    m_client(new QTcpSocket(this))
{
    connect(m_client, SIGNAL(connected()), SLOT(onConnected()));
    connect(m_client, SIGNAL(disconnected()), SLOT(onDisconnected()));
    connect(m_client, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onDisconnected()));
    connect(m_client, SIGNAL(readyRead()), SLOT(onReadyRead()));
}

void TcpClient::cleanup()
{
    closeConnect();
    delete m_client;
    m_client = nullptr;
}

bool TcpClient::connectServer(const QHostAddress &ip, int port)
{
    if (m_client->isOpen()) {
        m_client->abort();
    }
    m_client->connectToHost(ip, port);

    return true;
}

bool TcpClient::closeConnect()
{
    if (m_client->isOpen()) {
        m_client->abort();
    }

    return !m_client->isOpen();
}

void TcpClient::sendMsgToClient(const QByteArray &msg)
{
    m_client->write(msg.data(), msg.length());

    m_sendMsgLenCnt += msg.size();
    emit sigCNTUpdate(m_sendMsgLenCnt, m_revMsgLenCnt);
}

void TcpClient::onConnected()
{
    qInfo().noquote() << tr("TcpClient: %1:%2 connected, localport=%3")
                         .arg(m_client->peerName())
                         .arg(m_client->peerPort())
                         .arg(m_client->localPort());
    m_isOnline = true;
    emit sigIsOnline(true);
}

void TcpClient::onDisconnected()
{
    qInfo().noquote() << tr("TcpClient: tcp disconnected");
    m_client->disconnectFromHost();
    m_isOnline = false;
    emit sigIsOnline(false);
}

// 系统接收控制消息，发送信号
void TcpClient::onReadyRead()
{
    QByteArray body = m_client->readAll();
    if(body.isEmpty()) {
        return;
    }

    m_revMsgLenCnt += body.size();
    emit sigReadMsg(MainWindow::getIpAndPortStr(m_client->peerAddress(), m_client->peerPort()), body);
    emit sigCNTUpdate(m_sendMsgLenCnt, m_revMsgLenCnt);
    qInfo() << "TcpServer: Msg header error:" << m_client->peerName() << body;
}
